<?php namespace App\Controllers\Frontend;

//http://www.codeforest.net/laravel4-simple-website-with-backend-1

use App\Models\Page;
use App\Models\PageTemplate;
use App\Models\PageRow;
use App\Models\PageBlock;
use App\Models\ProductCategory;
use App\Models\Product;
use Input, Redirect, Sentry, Str;
use Notification;

class PageController extends \BaseController {

	public function getPage( $params="" )
	{
		$homeslug = Page::where("is_homepage", 1)->first()->slug; 
		$components = explode("/", $params);

		$slug = (count($components) > 0)?array_shift($components):$homeslug;
		$slug = ($slug == "")?$homeslug:$slug;

		// get the actual page
		$page = Page::where("slug", $slug)->first();

		// if no such page, default to home page
		if(count($page) == 0)
		{
			$slug = $homeslug;
			$page = Page::where("is_homepage", 1)->first();
		}

		$layout = $page->template()->name;

		$params = array();
		$n = ""; $v = "";
		for($i=0; $i < count($components); $i++)
		{
			if($i%2 == 0)
			{
				$n = $components[$i];
			}
			else
			{
				$v = $components[$i];
				$params[$n] = $v;
			}
		}

		return \View::make("frontend._layouts.".$layout)
			->with("slug", $slug)
			->with("page", $page)
			->with("layout", $layout)
			->with("nav", $this->getStructuredList(0))
			//->with("params", implode("/", $components))
			//->with("params", $params)
			->with("params", $components);
	}

	public function getStructuredList($parentid=0, $id="pagelist")
	{
		$html = "<ul id='$id-$parentid' class='clearfix'>";

		$subs = Page::where("parentid", $parentid)->where("status", 1)->orderby("pageorder")->get();

		foreach ($subs as $child) {
			$current_id = $child->id;
			
			$numkids = Page::where("parentid", $current_id)->count();

			if($numkids > 0 || strtolower($child->slug) == "products")
			{
				$html .= "<li data-pageid='$current_id' class='haskids'>";
			}
			else
			{
				$html .= "<li data-pageid='$current_id'>";
			}
			
			
			if($child->is_homepage)
			{
				$html.= "<a href='/'>";
			}
			else
			{
				$html .= "<a href='/{$child->slug}'>";
			}

			if($numkids > 0 || strtolower($child->slug) == "products")
			{
				$html.='<i class="fa fa-fw fa-caret-down"></i>';
			}

			$html .= "{$child->name}</a>";

			if(strtolower($child->slug) == "products")
			{
				$cats = ProductCategory::getCategoryListMenu(0, "", "product-categories");
				$html.= $cats;
			}
			else
			{
				if($numkids > 0)
				{
					$html .= $this->getStructuredList($current_id, $id);
				}
			}

			$html .= "</li>";
		}
		$html .= "</ul>";
		return $html;
	}
}